package com.caishi.lkx.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.caishi.lkx.common.AclResultCode;
import com.caishi.lkx.common.CommonResultCode;
import com.caishi.lkx.common.PushService;
import com.caishi.lkx.common.config.DiamondConfig;
import com.caishi.lkx.common.ienum.DeviceType;
import com.caishi.lkx.user.dto.LoginDto;
import com.caishi.lkx.user.ienum.status.UserStatus;
import com.caishi.lkx.user.ienum.type.Sex;
import com.caishi.lkx.user.ienum.type.UserAccountType;
import com.caishi.lkx.user.ienum.type.UserChannelType;
import com.caishi.lkx.user.ienum.type.UserType;
import com.caishi.lkx.user.mapper.UserMapper;
import com.caishi.lkx.user.model.*;
import com.caishi.lkx.user.service.*;
import com.caishi.lkx.user.vo.SimpleUserVo;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.IBaseMapper;
import com.zzw.common.entity.impl.BaseEntity;
import com.zzw.common.exception.BizException;
import com.zzw.common.exception.BizRuntimeException;
import com.zzw.common.lock.RedissonLock;
import com.zzw.common.service.service.impl.BaseServiceImpl;
import com.zzw.common.threadpool.SysThreadPool;
import com.zzw.common.utils.UUIDUtil;

import com.caishi.lkx.user.UserResultCode;

import com.caishi.lkx.user.login.LoginServiceComposite;

import com.caishi.lkx.user.mongo.UserLoginVersionMongoRepository;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.redisson.api.RLock;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

/**
 * @author by keray
 * date:2019/8/1 15:17
 */
@Service(value = "baseUserService")
@Slf4j
@Primary
public class UserServiceImpl extends BaseServiceImpl<UserModel> implements IUserService<UserModel> {

    @Resource
    private IMemberService memberService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ILoginInfoService loginInfoService;

    @Resource
    private DiamondConfig diamondConfig;

    @Resource
    private IActionRoleService actionRoleService;

    @Resource
    private MongoTemplate template;

    @Resource
    private LoginServiceComposite loginServiceComposite;

    @Resource
    private PushService pushService;

    @Resource
    private UserLoginVersionMongoRepository userLoginVersionMongoRepository;

    @Resource
    private IAgentUserService agentUserService;

    @Override
    public IBaseMapper<UserModel, String> getMapper() {
        return userMapper;
    }

    @Override
    public UserModel update(UserModel entity) {
        if (ObjectUtil.isEmpty(entity.getId())) {
            throw new BizRuntimeException("update必须拥有Id", CommonResultCode.dataChangeError.getCode());
        }
        return getMapper().updateById(entity) == 1 ? entity : null;
    }

    @Override
    public UserModel simpleUpdate(UserModel entity) {
        if (ObjectUtil.isEmpty(entity.getId())) {
            throw new BizRuntimeException("update必须拥有Id", CommonResultCode.dataChangeError.getCode());
        }
        return getMapper().updateById(entity) == 1 ? entity : null;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<String> strings) {
        userMapper.deleteBatchIds(strings);
        loginInfoService.delete(Wrappers.<LoginInfoModel>lambdaUpdate().in(LoginInfoModel::getUserId, strings));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(String s) {
        userMapper.deleteById(s);
        loginInfoService.delete(Wrappers.<LoginInfoModel>lambdaUpdate().eq(LoginInfoModel::getUserId, s));
        return true;
    }

    @Override
    public int delete(LambdaUpdateWrapper<UserModel> wrapper) {
        throw new BizRuntimeException();
    }

    @Override
    public int delete(UpdateWrapper<UserModel> wrapper) {
        throw new BizRuntimeException();
    }

    @Override
    public IUserService<UserModel> baseService() {
        return this;
    }

    @Override
    public UserModel register(LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) throws BizException {
        throw new BizException();
    }

    @Override
    public UserModel register(UserModel userModel) {
        Assert.notNull(userModel.getUserType(), "用户登录类型不能为空");
        Assert.isNull(userModel.getId());
        if (!userModel.userTypeOne()) {
            throw new BizRuntimeException("错误的数据");
        }
        return commonRegister(userModel);
    }

    @Override
    public UserModel bindPhone(UserModel currentUser, String phone) {
        if (StrUtil.isBlank(currentUser.getId())) {
            throw new BizRuntimeException();
        }
        if (StrUtil.isNotBlank(currentUser.getMobile())) {
            throw new BizRuntimeException(UserResultCode.userHaveBindMobile);
        }

        try {
            RLock rLock = RedissonLock.lock("third_bind_" + currentUser.getId());
            // 保证手机号只会绑定一次
            TransactionSynchronizationManager.registerSynchronization(
                    new TransactionSynchronization() {
                        @Override
                        public void afterCompletion(int status) {
                            if (!Thread.currentThread().isInterrupted()) {
                                rLock.unlock();
                                return;
                            }
                            throw new BizRuntimeException();
                        }
                    }
            );
        } catch (InterruptedException | TimeoutException e) {
            throw new BizRuntimeException(e);
        }
        var oldUser = getUserByMobile(phone);
        if (null == oldUser) {
            loginInfoService.userAddNewLogin(phone, null, UserAccountType.phone, currentUser.getId());
            currentUser.setMobile(phone);
            this.update(currentUser);
            return currentUser;
        } else {
            int r = loginInfoService.getUserHaveLogin(currentUser.getId()) & loginInfoService.getUserHaveLogin(oldUser.getId());
            if (r != 0) {
                throw new BizRuntimeException(UserResultCode.mobileHaveBind);
            }
            LoginInfoModel build = LoginInfoModel.builder().userId(oldUser.getId()).build();
            loginInfoService.batchUpdate(build, Wrappers.<LoginInfoModel>lambdaUpdate().eq(LoginInfoModel::getUserId, currentUser.getId()));
            oldUser.addUserType(currentUser.getUserType());
            currentUser.setUserStatus(UserStatus.off);
            simpleUpdate(oldUser);
            simpleUpdate(currentUser);
            return oldUser;
        }
    }


    @Override
    public UserModel getUserDetail(String userId, UserModel baseUser) {
        return this.getById(userId);
    }

    @Override
    public boolean mobileExits(String mobile, String oldMobile) {
        return userMapper.selectCount(
                wrappers()
                        .eq(UserModel::getMobile, mobile)
                        .ne(StrUtil.isNotBlank(oldMobile), UserModel::getMobile, oldMobile)
                        .ne(IUserModel::getUserStatus, UserStatus.off)
        ) > 0;
    }

    @Override
    public SimpleUserVo userSimpleMsg(String userId) {
        UserModel userModel = getById(userId);
        if (ObjectUtil.isEmpty(userModel)) {
            return SimpleUserVo.builder().name("已注销").build();
        }
        return SimpleUserVo.builder()
                .header(userModel.getHeader())
                .sex(userModel.getSex())
                .name(userModel.getName())
                .id(userId)
                .build();
    }

    @Override
    public String getUserRoleName(String userId) {
        String role = actionRoleService.apiRoleName(userId);
        UserModel userModel = selectOne(wrappers().select(IUserModel::getUserType, IUserModel::getApiRoleName).eq(BaseEntity::getId, userId));

        List<String> userRules = Arrays.stream(UserType.int2Array(userModel.getUserType()))
                .filter(v -> v != UserType.admin)
                .map(Enum::name).collect(Collectors.toList());
        if(StrUtil.isNotBlank(role))
            userRules.addAll(Arrays.asList(role.split(",")));
        if(StrUtil.isNotBlank(userModel.getApiRoleName()))
            userRules.addAll(Arrays.asList(userModel.getApiRoleName().split(",")));
        return userRules.stream().distinct().filter(StrUtil::isNotBlank).collect(Collectors.joining(","));


//        return role;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lockUser(boolean unLock, String userId) {
        loginInfoService.changeLoginInfoEnable(userId, unLock);
        userMapper.update(null, Wrappers.<UserModel>lambdaUpdate()
                .set(UserModel::getUserStatus, unLock ? UserStatus.normal : UserStatus.lock)
                .eq(UserModel::getId, userId)
        );
    }

    @Override
    public boolean userIsHaveRole(String userId, UserType userType) {
        return userTypes(userId).contains(userType);
    }


    private UserModel commonRegister(UserModel userModel) {
        if (StrUtil.isNotBlank(userModel.getMobile())) {
            try {
                RLock rLock = RedissonLock.lock("bind" + userModel.getMobile());
                // 保证手机号只会绑定一次
                TransactionSynchronizationManager.registerSynchronization(
                        new TransactionSynchronization() {
                            @Override
                            public void afterCompletion(int status) {
                                if (!Thread.currentThread().isInterrupted()) {
                                    rLock.unlock();
                                    return;
                                }
                                throw new BizRuntimeException();
                            }
                        }
                );
            } catch (InterruptedException | TimeoutException e) {
                throw new BizRuntimeException(e);
            }
            UserModel oldModel = userMapper.selectOne(wrappers()
                    .eq(IUserModel::getMobile, userModel.getMobile())
                    .ne(IUserModel::getUserStatus, UserStatus.off)
            );
            // 新增用户类型 基础表对应多个扩展表
            if (oldModel != null) {
                if (UserType.intHaveType(oldModel.getUserType(), UserType.int2Obj(userModel.getUserType()))) {
                    throw new BizRuntimeException(UserResultCode.registerMobileExits);
                }
                // 新增用户类型
                oldModel.addUserType(userModel.getUserType());
                oldModel.addApiRoleName(userModel.getApiRoleName());
//                if (StrUtil.isNotBlank(userModel.getName())) {
//                    oldModel.setName(userModel.getName());
//                }
                if (userModel.getSex() != null && userModel.getSex() != Sex.unknown) {
                    oldModel.setSex(userModel.getSex());
                }
                if (StrUtil.isNotBlank(userModel.getHeader())) {
                    oldModel.setHeader(userModel.getHeader());
                }
                if (StrUtil.isNotBlank(oldModel.getMobile())) {
                    LoginInfoModel loginInfoModel = loginInfoService.selectLoginInfoUserAccount(oldModel.getMobile(), UserAccountType.phone);
                    if (null == loginInfoModel) {
                        loginInfoService.userAddNewLogin(oldModel.getMobile(), null, UserAccountType.phone, oldModel.getId());
                    }
                }
                return this.update(oldModel);
            }
        }
        // 设置基本信息
        if (StrUtil.isBlank(userModel.getName())) {
            // 设置默认名称
            userModel.setName("神秘用户");
        }
        if (StrUtil.isBlank(userModel.getHeader())) {
            // 设置默认头像
            userModel.setHeader(diamondConfig.getUserDefaultHeader());
        }
        // 真正新增用户
        userModel.setId(generateUserId(UserType.int2Obj(userModel.getUserType())));
        // 如果有手机号，会插入两次，一个无密码，一个有密码？
        if (StrUtil.isNotBlank(userModel.getMobile())) {
            loginInfoService.userAddNewLogin(userModel.getMobile(), null, UserAccountType.phone, userModel.getId());
        }
        return super.insert(userModel);
    }


    public List<UserType> userTypes(String userId) {
        UserModel userModel = selectOne(wrappers().select(UserModel::getUserType).eq(BaseEntity::getId, userId));
        if (null == userModel) {
            return null;
        }
        return Arrays.asList(userModel.getUserTypes());
    }

    public void addUserType(UserType userType, String userId) {
        this.update(null, Wrappers.<UserModel>lambdaUpdate()
                .setSql(StrUtil.format("user_type = user_type | {}", userType.getValue()))
                .eq(BaseEntity::getId, userId)
        );
        this.updateUserLoginVersion(userId);
    }

    public void delUserType(UserType userType, String userId) {
        this.update(null, Wrappers.<UserModel>lambdaUpdate()
                .setSql(StrUtil.format("user_type = user_type & ~{}", userType.getValue()))
                .eq(BaseEntity::getId, userId)
        );
        this.updateUserLoginVersion(userId);
    }

    @SneakyThrows
    public void addUserApiRule(String apiRule, String userId) {
        UserModel userModel = this.selectOne(wrappers().select(UserModel::getApiRoleName).eq(BaseEntity::getId, userId));
        RedissonLock.lock("addUserApiRule" + userId, key -> {
            userModel.addApiRoleName(apiRule);
            this.simpleUpdate(userModel);
        });
        this.updateUserLoginVersion(userId);
    }

    @SneakyThrows
    public void delUserApiRule(String apiRule, String userId) throws InterruptedException, TimeoutException {
        UserModel userModel = this.selectOne(wrappers().select(UserModel::getApiRoleName).eq(BaseEntity::getId, userId));
        RedissonLock.lock("addUserApiRule" + userId, key -> {
            userModel.delApiRoleName(apiRule);
            this.simpleUpdate(userModel);
        });
        this.updateUserLoginVersion(userId);
    }


    @Override
    public List<UserModel> selectListByPhoneOrAdd(List<String> userPhone, String agentUserId) {
        List<UserModel> userModels = this.selectList(Wrappers.<UserModel>lambdaQuery().in(UserModel::getMobile, userPhone).ne(UserModel::getUserStatus, UserStatus.off));
        List<String> collect = userModels.stream().map(IUserModel::getMobile).toList();
        userPhone.removeAll(collect);
        if (CollUtil.isNotEmpty(userPhone)) {
            List<UserModel> collect1 = userPhone.stream().map(phone -> {
                MemberModel member = new MemberModel();
                member.addUserType(UserType.member);
                member.setMobile(phone);
                member.setChannelType(UserChannelType.pcAdmin7);
                member.setChannelPointer(agentUserId);
                member.setGroupId(agentUserService.getById(agentUserId).getBindGroupId());
                try {
                    return loginServiceComposite.register(LoginInfoModel.builder()
                            .account(phone)
                            .loginType(UserAccountType.username)
                            .certificate(diamondConfig.getUserDefaultPassword())
                            .build(), member).toUserModel();
                } catch (BizException e) {
                    e.printStackTrace();
                    throw new BizRuntimeException(UserResultCode.registerFail);
                }
            }).toList();
            userModels.addAll(collect1);
        }
        return userModels;
    }


    // userLoginVersion有关
    private String generateUserId(UserType userType) {
        return UUIDUtil.generateUUIDByTimestamp();
    }

    public String updateUserLoginVersion(String userId) {
        String version = UUIDUtil.generateUUIDByTimestamp();
        var versionData = userLoginVersionMongoRepository.findOne(Example.of(UserLoginVersionModel.builder().userId(userId).build())).orElse(null);
        SysThreadPool.execute(() -> {
            try {
                if (versionData == null) return;
                pushService.sendProjectMessage(versionData.getPcUUid(), "upVersion", MapUtil.builder()
                        .put("userId", userId)
                        .build(), PushService.PushType.online, 0);
            } catch (Exception e) {
                log.error("挤下线消息推送失败", e);
            }
        });

        template.upsert(
                query(where("userId").is(userId)),
                Update.update("version", version),
                UserLoginVersionModel.class);
        return version;
    }

    public void updateUserLoginVersionUUid(String userId, DeviceType deviceType, String uuid) {
        Query query = query(where("userId").is(userId));
        Update update = null;
        if (deviceType == DeviceType.pc) {
            update = Update.update("pcUUid", uuid);
        } else if (deviceType == DeviceType.admin) {
            update = Update.update("adminPcUUid", uuid);
        } else if (deviceType == DeviceType.android) {
            update = Update.update("androidUUid", uuid);
        } else if (deviceType == DeviceType.ios) {
            update = Update.update("iosUUid", uuid);
        } else if (deviceType == DeviceType.wxcx) {
            update = Update.update("xcxUUid", uuid);
        } else {
            update = Update.update("otherUUid", uuid);
        }
        var versionData = template.findOne(query, UserLoginVersionModel.class);
        if (deviceType == DeviceType.pc && userVersionIsOver(versionData, deviceType, uuid)) {
            SysThreadPool.execute(() -> {
                try {
                    pushService.sendProjectMessage(versionData.getPcUUid(), AclResultCode.busyLine.name(), MapUtil.builder()
                            .put("duid", versionData.getPcUUid())
                            .put("userId", userId)
                            .build(), PushService.PushType.online, 0);
                } catch (Exception e) {
                    log.error("挤下线消息推送失败", e);
                }
            });
        }
        template.upsert(query, update, UserLoginVersionModel.class);
    }

    public String getUserLoginVersion(String userId) {
        UserLoginVersionModel model = getUserLoginVersionData(userId);
        if (model != null) {
            return model.getVersion();
        }
        return null;
    }

    public String getUserLoginUUid(UserLoginVersionModel model, DeviceType deviceType) {
        if (model != null) {
            if (deviceType == DeviceType.pc) {
                return model.getPcUUid();
            } else if (deviceType == DeviceType.admin) {
                return model.getAdminPcUUid();
            } else if (deviceType == DeviceType.android) {
                return model.getAndroidUUid();
            } else if (deviceType == DeviceType.ios) {
                return model.getIosUUid();
            } else if (deviceType == DeviceType.wxcx) {
                return model.getXcxUUid();
            } else {
                return model.getOtherUUid();
            }
        }
        return "";
    }


    public UserLoginVersionModel getUserLoginVersionData(String userId) {
        return template.query(UserLoginVersionModel.class).matching(where("userId").is(userId)).oneValue();
    }

    public boolean userVersionIsOver(String userId, DeviceType deviceType, String duid) {
        var versionData = userLoginVersionMongoRepository.findOne(Example.of(UserLoginVersionModel.builder().userId(userId).build())).orElse(null);
        return userVersionIsOver(versionData, deviceType, duid);
    }

    public boolean userVersionIsOver(UserLoginVersionModel versionData, DeviceType deviceType, String duid) {
        // 目前就管理端限制只能一个登录
        if (deviceType == DeviceType.admin) {
            if (versionData == null) return false;
            var saveDuid = getUserLoginUUid(versionData, deviceType);
            return !StrUtil.isBlank(saveDuid) && saveDuid.equals(duid);
        }
        return false;
    }

//    public RpcUserModel rpcGetById(String s) {
//        var userModel = getById(s);
//        if (null == userModel) {
//            return null;
//        }
//        return RpcUserModel.model(userModel);
//    }

//    @Override
//    public void updateUserName(String id, String username) {
//        update(null, Wrappers.<UserModel>lambdaUpdate()
//                .set(IUserModel::getName, username)
//                .eq(BaseEntity::getId, id)
//        );
//    }
//
//    @Override
//    public RpcUserModel rpcSelectOneByMobile(String mobile) {
//        return RpcUserModel.model(selectOne(wrappers().eq(IUserModel::getMobile, mobile).ne(IUserModel::getUserStatus, UserStatus.off)));
//    }
//
//    @Override
//    @Transactional
//    public RpcUserModel rpcUpdate(RpcUserModel model) {
//        var userModel = BeanUtil.copyProperties(model, UserModel.class);
//        return RpcUserModel.model(update(userModel));
//    }
//
//    @Override
//    @Transactional
//    public int rpcDeleteBatchIds(List<String> ids) {
//        return Boolean.TRUE.equals(delete(ids)) ? 1 : 0;
//    }
//
//    @Override
//    public RpcUserModel rpcSelectUserByMobile(String mobile, String oldMobile) {
//        var model = selectFirst(wrappers()
//                .eq(UserModel::getMobile, mobile)
//                .ne(StringUtil.isNotBlank(oldMobile), UserModel::getMobile, oldMobile)
//                .ne(IUserModel::getUserStatus, UserStatus.off));
//        return RpcUserModel.model(model);
//    }
//
//    @Override
//    public void rpcUpdateUserStatus(boolean unLock, String userId) {
//        update(null, Wrappers.<UserModel>lambdaUpdate()
//                .set(UserModel::getUserStatus, unLock ? UserStatus.normal : UserStatus.lock)
//                .eq(UserModel::getId, userId)
//        );
//    }
//
//    @Override
//    public RpcUserModel rpcInsert(RpcUserModel model) {
//        var userModel = BeanUtil.copyProperties(model, UserModel.class);
//        return RpcUserModel.model(insert(userModel));
//    }
//
//    @Override
//    public void rpcUpdateUserPhone(String id, String phone) {
//        update(null, Wrappers.<UserModel>lambdaUpdate()
//                .set(IUserModel::getMobile, phone)
//                .eq(BaseEntity::getId, id));
//    }
//
//    @Override
//    public void rpcUpdateUserType(Integer value, String userId) {
//        update(null, Wrappers.<UserModel>lambdaUpdate()
//                .setSql(StrUtil.format("user_type = user_type | {}", value))
//                .eq(BaseEntity::getId, userId)
//        );
//    }
//
//    @Override
//    public List<RpcUserModel> rpcSelectListByPhone(List<String> userPhone) {
//        List<UserModel> userModels = this.selectList(Wrappers.<UserModel>lambdaQuery().in(UserModel::getMobile, userPhone).eq(UserModel::getUserStatus, UserStatus.normal));
//        return userModels.parallelStream().map(RpcUserModel::model).collect(Collectors.toList());
//    }
//
//    @Override
//    public List<RpcGroupMemberUser> rpcUserListByIds(List<String> ids) {
//        List<UserModel> userModels = this.selectBatchIds(ids);
//        return new ArrayList<>(ids.parallelStream().map(m -> RpcGroupMemberUser.model(memberService.getUserDetail(m))).toList());
//    }
//
//    @Override
//    public List<RpcGroupMemberUser> rpcSelectListByPhoneOrName(String name, String phone) {
//        return null;
//    }
//
//    @Override
//    public RpcUserModel rpcRegister(RpcLoginInfoModel rpcLoginInfoModel, RpcMemberModel model) throws BizException {
//        var loginInfoModel = BeanUtil.copyProperties(rpcLoginInfoModel, LoginInfoModel.class);
//        var memberModel = BeanUtil.copyProperties(model, MemberModel.class);
//        memberModel.setHaveType(HaveType.ykt.getValue());
//        var userModel = loginServiceComposite.register(loginInfoModel, memberModel).toUserModel();
//        return RpcUserModel.model(userModel);
//    }
//
//    @Override
//    public String rpcGetUserRoleName(String userId) {
//        return this.getUserRoleName(userId);
//    }
//
//    @Override
//    public String rpcGetUserLoginVersion(String userId) {
//        return this.getUserLoginVersion(userId);
//    }
//
//    @Override
//    public String rpcUpdateUserLoginVersion(String userId) {
//        return this.updateUserLoginVersion(userId);
//    }
//
//    @Override
//    public void rpcUpdateUserLoginVersionUUid(String userId, RpcDeviceType deviceType, String uuid) {
//        this.updateUserLoginVersionUUid(userId, DeviceType.rpcType(deviceType), uuid);
//    }
//
//    public Boolean updateHaveType(HaveType haveType, String userId) {
//        UserModel userModel = this.getById(userId);
//        if (null == userModel) return false;
//        return this.updateHaveType(haveType, userModel);
//    }
//
//    public Boolean updateHaveType(HaveType haveType, UserModel userModel) {
//        userModel.addHaveType(haveType);
//        return null != this.update(userModel);
//    }
//
//    @Override
//    @Transactional
//    public Boolean rpcDelete(String id) {
//        return this.delete(id);
//    }

}
